<template>
	<Layout class="layout-container">
		<Content>
			<Spin fix v-if="loading"></Spin>
			<Form ref="form" :model="value" :rules="rules" label-position="left" :label-width="120">
				<Layout class="layout-container">
					<Content class="padding-all">
			            <FormItem :label="label.name" prop="name">
			                <Input type="text" v-model="value.name" :placeholder="placeholder.name" />
			            </FormItem>
			            <FormItem :label="label.memo" prop="memo">
			                <Input 
		                    	v-model="value.memo"
		                    	type="textarea"
		                    	:rows="3"
		                    	:placeholder="placeholder.memo" />
			            </FormItem>
					</Content>
					<div class="padding-all">
		    			<span class="pull-right">
						<Button @click="reset">{{$t('info.reset')}}</Button>
						<Button 
							type="primary" 
							html-type="submit" 
							@click.prevent="submit">{{$t('info.submit')}}</Button>
						</span>
					</div>
				</Layout>
			</Form>
		</Content>
	</Layout>
</template>
<script type="text/javascript">
import { Layout, Content, Spin, Form, FormItem, Button, Input } from 'view-design';
import { merror } from 'config/utils';

//校验
const URI_VALIDATE = '/security/api/router/validateNameForAdd';
//提交
const URI_SUBMIT = '/security/api/router/add';

export default {
	name: "SysRouterAdd",
	data() {
		var label = {
			name: this.$t("sys.router.name"),
			memo: this.$t("sys.memo")
		};
		return {
			loading: false,
			label,
			placeholder: {
				name: this.$t("info.placeholder", [label.name]),
				memo: this.$t('info.placeholder', [label.memo])
			},
			value: {
				name: '',
				memo: ''
			},
			rules: {
				name: [
					{
						label: label.name,
						required: true,
						max: 200,
						trigger: 'blur'
					},
					{
						message: this.$t('valid.unique', [label.name]),
						validate: (value, rule, label, messages) => {
							//校验ID是否唯一
						    return new Promise(resolve => {
						    	this.$http.post(URI_VALIDATE, {
						    		name: value
						    	}).then((response) => {
						    		resolve(response.data == true);
						    	});
						    });
						},
						trigger: 'blur'
					}
				],
				memo: {
					label: label.memo,
					max: 100,
					trigger: 'blur'
				}
			}
		};
	},
	methods: {
		submit() {
			this.$refs.form.validate((valid) => {
				if(valid) {
					this.loading = true;
					this.$http.post(URI_SUBMIT, this.value).then((response) => {
						var res = response.data;
						if(res.success) {
							//回调
							this.$emit('callback');
							//关闭窗口
							this.$emit('close');
						} else if(res.code == 1) {
							merror(this.$t("valid.unique", [this.label.name]));
						}
						this.loading = false;
					});
				}
			});
			return false;
		},
        reset() {
            this.$refs.form.resetFields();
        }
	},
	components: {
		Layout,
		Content,
		Spin,
		Form,
		FormItem,
		Button,
		Input
	}
}
</script>